<template>
    <div>
      <el-input
        v-model="inputValue"
        readonly
        style="width:100%;"
        placeholder="请选择"
        v-if="props.type == 'single'"
      >
        <template #append><el-link :underline="false" @click="showList">点击选择</el-link></template>
      </el-input>
      <template v-else>
        <el-tag class="mr-2" v-for="(item,index) in selectList" :key="index" :closable="props.type == 'multiple'" @close="removeSelect(index)">
          {{ item[newOptions.name] }}
        </el-tag>
        <el-button type="default" @click="showList">点击选择</el-button>
      </template>
      <el-dialog
        v-model="isShow"
        :close-on-click-modal="false"
        width="500"
        append-to-body
        @close="handleClose"
      >
        <el-form :inline="true" :model="searchForm">
            <el-form-item>
              <el-input v-model="searchForm.name" clearable :placeholder="'请输入'+newOptions.title" />
            </el-form-item>
            <el-form-item>
             <el-button type="primary" @click="getList()">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table
            v-loading="tableData.loading"
            ref="refTable"
            :data="tableData.list"
            :header-cell-style="tableData.headerCellStyle"
            stripe
            border
            size="small"
            style="width: 100%"
            max-height="250"
            >
            <!-- <el-table-column label="序号" type="index" width="60"/> -->
            <el-table-column label="ID" prop="id" />
            <el-table-column :label="newOptions.title" prop="name" />
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  text
                  :disabled="props.type == 'multiple' && checkSelect(scope.row)"
                  @click="handleSelect(scope.row)"
                >选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="newOptions.isPage"
            size="small"
            :current-page="pageData.current"
            :page-size="pageData.size"
            :page-sizes="pageData.pageSizes"
            :total="pageData.total"
            background
            layout="total, prev, pager, next"
            @current-change="getList"
            @size-change="sizeChange"
          />
          <el-descriptions :column="1" border size="small" direction="vertical" class="mt-4" v-if="selectList.length > 0 && props.type == 'multiple'">
            <el-descriptions-item label="已选择">         
              <el-tag class="mr-2" v-for="(item,index) in selectList" :key="index" :closable="props.type == 'multiple'" @close="removeSelect(item)">
                {{ item[newOptions.name] }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="isShow = false">关闭</el-button>
            <!-- <el-button type="primary" @click="confirmSelect" v-if="props.type == 'multiple'">确定</el-button> -->
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  <script setup lang="ts">
  const {proxy} :any = getCurrentInstance() as ComponentInternalInstance;
  const emit = defineEmits(['update:modelValue','confirm']);
  
  const refTable = ref();
  let isShow = ref(false);
  let inputValue = ref();
  let searchForm = reactive(
    {name: null}
  );
  let tableData = reactive({
    loading: true,// 加载
    list: [],// 表格数据
    cellStyle: { textAlign: 'center' },
      headerCellStyle: {
          background: 'var(--el-table-row-hover-bg-color)',
          color: 'var(--el-text-color-primary)',
      },
    select: [],
  });
  let pageData = reactive({
    pageNum: 1,
    pageSize: 10,
    pageSizes: [10,15,30,50,100],
    total: 0
  });
  
  const props = defineProps({
      modelValue: {type: Array},
      api: {type: String},
      options: {type: Object},
      size: {type: String, default: () => 'enum'},
      type: {type: String, default: () => 'single'}, //单选single,多选multiple
      // selected: {type: Array, default: () => []}
  });
  const opts = reactive({
    id: 'id',
    name: 'name',
    searchKey: 'searchValue',
    data: 'records',
    title: '名称',
    isPage: true,
  });
  const newOptions = computed({
    get(){
      return Object.assign({}, opts, props.options);
    },
    set(newVal){
      console.log(newVal);
    }
  });
  let selectList = computed({
    get(){
      return props.modelValue;
    },
    set(newVal){
      if(props.type == 'single' && newVal.length > 0){
        inputValue.value = newVal[0][newOptions.name];
      }
    }
  });
  const getList = (page:number = 1) => {
      let params = {
        pageNum: page,
        pageSize: pageData.pageSize
      };
      params[newOptions.value.searchKey] = searchForm.name;
      tableData.loading = true;
      return new Promise((resolve, reject) => {
        proxy.$request('get', props.api, params, (data:any,msg:any) => {
          let list;
          if(newOptions.value.data == 'data'){
            list = data;
          }else{
            list = data[newOptions.value.data];
          }
          if(list.length > 0){
            tableData.list = list.map(item=>{
              item.id=item[newOptions.value.id];
              item.name=item[newOptions.value.name];
              return item
            });
          }
          pageData.total = data.total;
          tableData.loading = false;
          resolve(list);
        })
      })    
    };
    const sizeChange = (val:number) => {
      pageData.pageSize = val;
      getList(pageData.pageNum);
    };
  const showList = () => {
    isShow.value = true;
    if(tableData.list.length == 0){
      getList();
    }
  };
  const checkSelect = (row:any) => {
    let ids = selectList.value.map(item => item[newOptions.value.id]);
      if(ids.indexOf(row[newOptions.value.id]) != -1){
        return true;
      }else{
        return false;
      }
  };
  const removeSelect = (index) => {
      selectList.value.splice(index,1);
  };
  const handleSelect = (row:any) => {
    if(props.type == 'single'){
      emit('confirm', row);
      emit('update:modelValue', row);
      selectList.value = [row]
      inputValue.value = row[newOptions.value.name]
      isShow.value = false;
    }else{
      let ids = selectList.value.map(item => item[newOptions.value.id]);
      if(ids.indexOf(row[newOptions.value.id]) == -1){
        selectList.value.push(row);
      }
    } 
  }
  const handleClose = () => {
  
  };
  const confirmSelect = () => {
    isShow.value = false;
  }
  onMounted(() => {
    if(props.type == 'single' && selectList.value.length){
      inputValue.value = selectList.value[0][newOptions.value.name]
    }  
  })
  </script>